/*
 * Copyright (C) 2009 AnK Team
 *	 Andrey Korolev
 *	 Anna Krel
 *	 Anna Kapanina
 *	 
 *	 http://code.google.com/p/ankfood/	
 *    
     
 *    Licensed under the GNU General Public License, Version 2.0 (the "License");
 *
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *         http://www.gnu.org/licenses/gpl-2.0.html

 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,

 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */



package org.ank.food;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources.Theme;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class AddProductActivity extends Activity /*implements Runnable*/{ 
	
	public static final String INTENT_EXTRA_NAME_PROD_ID = "extra1";
	public static final String INTENT_EXTRA_NAME_SUBGROUP = "extra2";
	public static final int MAX_AMOUNT = 35;
	
	private static final int MESSAGE_WAIT = 0;
	private static final int MESSAGE_READY = 1;
	
	private StringBuffer recommendation;
	private Button addButton, cancelButton, cancel2Button;
	private ImageButton plusButton, minusButton;
//	private ProductDataManager prdm;
	private int amount, subGroup, prodId;
	private Spinner weightSpinner;
	private SimpleCursorAdapter adapter;
	private	TextView protValue, fatValue, carboValue, energyValue, amountView, recommendationView,
		addTitle, addSubTitle, indicatorView;
	private MHandler handler;
	private ProgressBar progressBar;
	private Thread t = null;
	
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.product_add_dialog);
        
        
        
//        ProductDataManager.getInstance(getApplicationContext()) = ProductDataManager.getInstance(getApplicationContext());
        
        plusButton = (ImageButton)findViewById(R.id.add_dialog_plus_button);
        minusButton = (ImageButton)findViewById(R.id.add_dialog_minus_button);
        addButton = (Button)findViewById(R.id.add_dialog_add_button);
        cancelButton = (Button)findViewById(R.id.add_dialog_cancel_button);
        cancel2Button = (Button)findViewById(R.id.add_dialog_cancel2_button);
        protValue = (TextView)findViewById(R.id.add_dialog_product_prot_value);
        fatValue = (TextView)findViewById(R.id.add_dialog_product_fat_value);
        carboValue = (TextView)findViewById(R.id.add_dialog_product_carbo_value);
        energyValue = (TextView)findViewById(R.id.add_dialog_product_energy_value);
        amountView = (TextView)findViewById(R.id.add_dialog_amount_textview);
        recommendationView = (TextView)findViewById(R.id.add_dialog_recommendation);
        weightSpinner = (Spinner)findViewById(R.id.add_dialog_spinner);
        progressBar = (ProgressBar)findViewById(R.id.add_product_progressbar);
        indicatorView = (TextView)findViewById(R.id.add_dialog_indicator);
        addTitle = (TextView)findViewById(R.id.add_dialog_add_title);
        addSubTitle = (TextView)findViewById(R.id.add_dialog_add_subtitle);
//        recommendationTitle = (TextView)findViewById(R.id.add_dialog_recommendation_title);
//        recommendationEnd = (TextView)findViewById(R.id.add_dialog_recommendation_end);
        
        amount = 1;
        amountView.setText(String.valueOf(amount));
        
        
        cancelButton.setOnClickListener(new Button.OnClickListener(){
			@Override
			public void onClick(View v) {
				
				
//				Intent intent = new Intent();
//				intent.setClass(getApplicationContext(), EatenTodayActivity.class);
//				startActivity(intent);
				if(t!=null)
					t.stop();
				finish();
			}
        });
        cancel2Button.setOnClickListener(new Button.OnClickListener(){
			@Override
			public void onClick(View v) {
				
				
//				Intent intent = new Intent();
//				intent.setClass(getApplicationContext(), EatenTodayActivity.class);
//				startActivity(intent);
				cancelButton.performClick();
			}
        });
        
        plusButton.setImageResource(R.drawable.plus_btn2);
        plusButton.setOnClickListener(new Button.OnClickListener(){
			@Override
			public void onClick(View v) {
				if(amount<MAX_AMOUNT){
					amount++;
					amountView.setText(String.valueOf(amount));
				}
			}
        });
        
        minusButton.setImageResource(R.drawable.minus_btn3);
        minusButton.setOnClickListener(new Button.OnClickListener(){
			@Override
			public void onClick(View v) {
				if(amount > 1){
					amount--;
					amountView.setText(String.valueOf(amount));
				}
			}
        });
        
        
        
        Intent parentIntent = getIntent();
//        ////Log.v("addProdAct","from intent = "+parentIntent.getIntExtra("a",
//				-100) );
////        ////Log.v("addProdAct","prodId "+parentIntent.getIntExtra(AddProductActivity.INTENT_EXTRA_NAME_PROD_ID,
////				-100) );
        
        prodId = parentIntent.getIntExtra(INTENT_EXTRA_NAME_PROD_ID, 0);
        setTitle(ProductDataManager.getInstance(getApplicationContext()).getProductNameById(prodId));
//        ////Log.v("addProdAct","prodId "+prodId);
//        subGroup = parentIntent.getIntExtra(INTENT_EXTRA_NAME_SUBGROUP, -2);
        recommendation = new StringBuffer();
        handler = new MHandler(recommendationView, recommendation, progressBar, indicatorView );
        
        ////Log.v("addProdAct","before thread");
//        Thread t = new Thread1();
////        Looper.prepare();
//        t.start();
        ////Log.v("addProdAct","after thread.start");
/*----------------------------------------------*/        
        
        ////Log.v("addProdAct","before protValue");
        protValue.setText(  String.valueOf( ProductDataManager.getInstance(getApplicationContext()).getProductProtValue(prodId) )  );
        protValue.append(" ");
        protValue.append(getString(R.string.gramm_name));
        
        ////Log.v("addProdAct","before fatValue");
        fatValue.setText(  String.valueOf( ProductDataManager.getInstance(getApplicationContext()).getProductFatValue(prodId) )  );
        fatValue.append(" ");
        fatValue.append(getString(R.string.gramm_name));
        
        ////Log.v("addProdAct","before carboValue");
        carboValue.setText(  String.valueOf( ProductDataManager.getInstance(getApplicationContext()).getProductCarboValue(prodId) )  );
        carboValue.append(" ");
        carboValue.append(getString(R.string.gramm_name));
        
        ////Log.v("addProdAct","before energyValue");
        energyValue.setText(  String.valueOf( ProductDataManager.getInstance(getApplicationContext()).getProductEnergyValue(prodId) )  );
        energyValue.append(" ");
        energyValue.append(getString(R.string.energy_unit_name));
        
        ////Log.v("addProdAct","before adapter creation");
        
        
        adapter = new SimpleCursorAdapter( getApplicationContext(),
        		android.R.layout.simple_spinner_item,
        		ProductDataManager.getInstance(getApplicationContext()).getWeightItemsForProduct(prodId),  
        		new String[]{
        			ProductDataProvider.COLUMN_NAMES_WEIGHT[ProductDataProvider.WEIGHT_NAME]
        		},
    			new int[] {android.R.id.text1} );
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        
        ////Log.v("addProdAct","before setadapter");
        
        weightSpinner.setAdapter(adapter);
        if(  weightSpinner.getCount() == 0 ){
			recommendationView.setText(R.string.add_dialog_no_info);
			plusButton.setVisibility(View.GONE);
			minusButton.setVisibility(View.GONE);
			amountView.setVisibility(View.GONE);
			weightSpinner.setVisibility(View.GONE);
			addButton.setVisibility(View.GONE);
			addTitle.setVisibility(View.GONE);
			addSubTitle.setVisibility(View.GONE);
			cancelButton.setVisibility(View.GONE);
			cancel2Button.setVisibility(View.VISIBLE);
			
			
			
		}
//        
//        
//
//        if( (recommendation = ProductDataManager.getInstance(getApplicationContext()).getRecommendedWeight(prodId) )  == null){
//        	recommendation = new StringBuffer(getString(R.string.add_product_not_recommended));
//        }else{
//        	recommendation.insert(0, ' ').
//        			insert(0, getString(R.string.add_product_not_more_than)).
//        			append("\n").
//        			append(getString(R.string.add_product_for_current_menu));
//        }
//        
//        recommendationView.setText(recommendation.toString());

/*----------------------------------------------*/        
        
        ////Log.v("addProdAct","before setlistener");
        weightSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
			@Override
			public void onItemSelected(AdapterView<?> parent, View arg1,
					int pos, long id) {
//				int amount;
//				if( (amount = ProductDataManager.getInstance(getApplicationContext()).getRecommendedAmountForWeightItem(prodId,(int)id)) == 0 ){
//					if(pos == 0){
//						recommendationView.setText(getString(R.string.add_product_not_recommended));
//						return;
//					}
//					recommendationView.setText(getString(R.string.add_product_recommended_less));
//					return;
//				}
//				recommendation = new StringBuffer(getString(R.string.add_product_not_more_than));
//				recommendation.append(' ').append(amount).append(" x ")
//						.append( ProductDataManager.getInstance(getApplicationContext()).getWeightItemNameById((int)id) ).append(' ')
//						.append(getString(R.string.add_product_for_current_menu));
//				recommendationView.setText(recommendation.toString());
				if(  ((Spinner)parent).getCount() == 0 ){
					recommendationView.setText(R.string.add_dialog_no_info);
					plusButton.setVisibility(View.GONE);
					minusButton.setVisibility(View.GONE);
					amountView.setVisibility(View.GONE);
					weightSpinner.setVisibility(View.GONE);
					addButton.setVisibility(View.GONE);
					
					
				}else{
					t = new Thread2(pos,id);
					t.start();
				}
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
        	
        });
        
        addButton.setOnClickListener(new Button.OnClickListener(){
			@Override
			public void onClick(View v) {
				
				
//				Intent intent = new Intent();
//				intent.setClass(getApplicationContext(), EatenTodayActivity.class);
//				startActivity(intent);
				int weightItemId = (int)weightSpinner.getSelectedItemId();
				
				AdviceManager.getInstance(getApplicationContext()).
						saveNewMenuItem(prodId, weightItemId, amount);
				setResult(RESULT_OK);
				finish();
			}
        });
        
        
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
//			Intent intent = new Intent();
//			intent.setClass(getApplicationContext(), ConfirmExperienceActivity.class);
//			intent.putExtra(ConfirmExperienceActivity.INTENT_EXTRA_NAME_MODE,
//					ConfirmExperienceActivity.SHOW_PRODUCTS_FROM_SUBGROUP_MODE);
//			
//			if(subGroup != -2){
//				////Log.v("addProdAct","sbgrp "+subGroup);
//				intent.putExtra(ConfirmExperienceActivity.INTENT_EXTRA_NAME_SUBGROUP,subGroup);
//			}
//			startActivity(intent);
			setResult(RESULT_CANCELED);
			finish();
			return true;
		}
	    return super.onKeyDown(keyCode, event);
	}
	
	
	public class Thread1 extends Thread{
		@Override
		public void run(){

		        
			////Log.v("addProdAct","inside thread");
				Message m = Message.obtain(handler, MESSAGE_WAIT);
				m.sendToTarget();
				StringBuffer buf;
			////Log.v("addProdAct","inside thread before get recommended weight");
		        if( (buf = ProductDataManager.getInstance(getApplicationContext()).getRecommendedWeightAsStrBuf(prodId) )  == null){
		        	
		        	recommendation.append( getString(R.string.add_product_not_recommended) );
		        }else{
		        	recommendation.append(buf);
		        	recommendation.insert(0, ' ').
		        			insert(0, getString(R.string.add_product_not_more_than)).
		        			append("\n").
		        			append(getString(R.string.add_product_for_current_menu));
		        }
		        ////Log.v("addProdAct","inside thread before finish");
		        m = Message.obtain(handler, MESSAGE_READY);
				m.sendToTarget();
//		        recommendationView.setText(recommendation.toString());
		        
		}

	}
	
	public class Thread2 extends Thread{
		private int pos;
		private long id;
		
		public Thread2(int p, long l){
			super();
			this.pos = p;
			this.id = l;
		}
		
		@Override
		public void run(){
			////Log.v("addProdAct","inside thread2");
			Message m = Message.obtain(handler, MESSAGE_WAIT);
			m.sendToTarget();
			m = Message.obtain(handler, MESSAGE_READY);
			recommendation.delete(0, recommendation.length());
			int amount = 0;
			if( (amount = ProductDataManager.getInstance(getApplicationContext()).getRecommendedAmountForWeightItem(prodId,(int)id)) == 0 ){
				if(pos == 0){
					recommendation.append(getString(R.string.add_product_not_recommended));
					m.sendToTarget();
					return;
				}
				recommendation.append(getString(R.string.add_product_recommended_less));
				m.sendToTarget();
				return;
			}
			recommendation.append(getString(R.string.add_product_not_more_than));
			recommendation.append(' ').append(amount).append(" x ")
					.append( ProductDataManager.getInstance(getApplicationContext()).getWeightItemNameById((int)id) ).append(' ')
					.append(getString(R.string.add_product_for_current_menu));
			////Log.v("addProdAct","inside thread2: rec = "+recommendation);
			
//	        m = Message.obtain(handler, MESSAGE_READY);
			m.sendToTarget();
//		        recommendationView.setText(recommendation.toString());
		        
		}

	}

	public class MHandler extends Handler{
		private TextView tv, indicator;
		private StringBuffer sb;
		private ProgressBar progBar;
		
		public MHandler(TextView t, StringBuffer b, ProgressBar pb, TextView i){
			super();
			this.tv = t;
			this.sb = b;
			this.progBar = pb;
			this.indicator = i;
		}
		@Override
		public void handleMessage(Message m){
			switch (m.what){
			
			case MESSAGE_WAIT :
				////Log.v("handler","message wait recived");
				progBar.setVisibility(View.VISIBLE);
				indicator.setVisibility(View.VISIBLE);
				
				break;
			case MESSAGE_READY :
				////Log.v("handler","message ready recived");
				progBar.setVisibility(View.INVISIBLE);
				indicator.setVisibility(View.INVISIBLE);
				tv.setText(sb.toString());
				
				break;
			}
		}
	}
	
}

